package com.rickpan.controller;

import com.rickpan.service.FilePreviewService;
import com.rickpan.utils.SecurityUtils;
import com.rickpan.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 文件预览控制器
 * 
 * @author RickPan Team
 * @since 2025-07-02
 */
@RestController
@RequestMapping("/api/preview")
public class FilePreviewController {

    @Autowired
    private FilePreviewService filePreviewService;

    /**
     * 视频流媒体预览
     * 支持Range请求，实现视频分段加载
     * 
     * @param fileId 文件ID
     * @param request HTTP请求
     * @return 视频流响应
     */
    @GetMapping("/video/{fileId}")
    public ResponseEntity<Resource> streamVideo(
            @PathVariable Long fileId,
            @RequestParam(required = false) String token,
            HttpServletRequest request) {

        try {
            Long currentUserId;

            // 如果有token参数，使用token认证
            if (token != null && !token.isEmpty()) {
                // TODO: 实现token验证逻辑，获取真实用户ID
                throw new BusinessException("Token认证功能暂未实现，请使用标准JWT认证");
            } else {
                // 使用标准JWT认证
                currentUserId = SecurityUtils.getCurrentUserId();
            }

            // 获取Range请求头
            String rangeHeader = request.getHeader(HttpHeaders.RANGE);

            // 调用流媒体服务
            return filePreviewService.streamVideo(fileId, currentUserId, rangeHeader);

        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 图片预览
     * 
     * @param fileId 文件ID
     * @return 图片资源
     */
    @GetMapping("/image/{fileId}")
    public ResponseEntity<Resource> previewImage(@PathVariable Long fileId) {
        try {
            Long currentUserId = SecurityUtils.getCurrentUserId();
            System.out.println("图片预览请求: userId=" + currentUserId + ", fileId=" + fileId);
            
            return filePreviewService.previewImage(fileId, currentUserId);
            
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
        }
    }

    /**
     * PDF预览
     * 
     * @param fileId 文件ID
     * @return PDF资源
     */
    @GetMapping("/pdf/{fileId}")
    public ResponseEntity<Resource> previewPdf(@PathVariable Long fileId) {
        try {
            Long currentUserId = SecurityUtils.getCurrentUserId();
            System.out.println("PDF预览请求: userId=" + currentUserId + ", fileId=" + fileId);
            
            return filePreviewService.previewPdf(fileId, currentUserId);
            
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
        }
    }

    /**
     * 文档预览（DOC/DOCX转HTML）
     *
     * @param fileId 文件ID
     * @return HTML预览内容
     */
    @GetMapping("/document/{fileId}")
    public ResponseEntity<String> previewDocument(@PathVariable Long fileId) {
        try {
            Long currentUserId = SecurityUtils.getCurrentUserId();
            System.out.println("文档预览请求: userId=" + currentUserId + ", fileId=" + fileId);
            
            String htmlContent = filePreviewService.convertDocumentToHtml(fileId, currentUserId);
            
            return ResponseEntity.ok()
                    .contentType(MediaType.TEXT_HTML)
                    .body(htmlContent);
                    
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("<html><body><h1>文档预览失败</h1><p>" + e.getMessage() + "</p></body></html>");
        }
    }

    /**
     * 表格预览（XLS/XLSX转JSON）
     * 
     * @param fileId 文件ID
     * @return JSON格式的表格数据
     */
    @GetMapping("/spreadsheet/{fileId}")
    public ResponseEntity<String> previewSpreadsheet(@PathVariable Long fileId) {
        try {
            Long currentUserId = SecurityUtils.getCurrentUserId();
            System.out.println("表格预览请求: userId=" + currentUserId + ", fileId=" + fileId);
            
            String jsonData = filePreviewService.convertSpreadsheetToJson(fileId, currentUserId);
            
            return ResponseEntity.ok()
                    .contentType(MediaType.APPLICATION_JSON)
                    .body(jsonData);
                    
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("{\"error\":\"表格预览失败\",\"message\":\"" + e.getMessage() + "\"}");
        }
    }

    /**
     * 获取文件预览信息
     *
     * @param fileId 文件ID
     * @return 预览信息
     */
    @GetMapping("/info/{fileId}")
    public ResponseEntity<String> getPreviewInfo(@PathVariable Long fileId) {
        try {
            Long currentUserId = SecurityUtils.getCurrentUserId();
            System.out.println("获取预览信息: userId=" + currentUserId + ", fileId=" + fileId);

            String previewInfo = filePreviewService.getPreviewInfo(fileId, currentUserId);

            return ResponseEntity.ok()
                    .contentType(MediaType.APPLICATION_JSON)
                    .body(previewInfo);

        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body("{\"error\":\"获取预览信息失败\",\"message\":\"" + e.getMessage() + "\"}");
        }
    }

    /**
     * 测试视频预览接口 - 无需认证
     * 仅用于开发调试
     */
    @GetMapping("/test/video/{fileName}")
    public ResponseEntity<Resource> testVideoPreview(@PathVariable String fileName) {
        try {
            System.out.println("测试视频预览: fileName=" + fileName);

            // 直接从uploads目录获取视频文件
            String videoPath = "2025/07/01/" + fileName;
            Path fullPath = Paths.get("./uploads").resolve(videoPath);
            File videoFile = fullPath.toFile();

            System.out.println("视频文件路径: " + fullPath.toAbsolutePath());
            System.out.println("文件存在: " + videoFile.exists());

            if (!videoFile.exists()) {
                return ResponseEntity.notFound().build();
            }

            Resource resource = new FileSystemResource(videoFile);

            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_TYPE, "video/mp4")
                    .header(HttpHeaders.CONTENT_LENGTH, String.valueOf(videoFile.length()))
                    .header(HttpHeaders.ACCEPT_RANGES, "bytes")
                    .body(resource);

        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}
